# -*- coding: utf-8 -*-
# created on 2016/01/11

from sympy import S, solve
from mathsolver.functions.base import BaseFunction, BasePoint, BaseNumber
from mathsolver.functions.daoshu.daoshuyunsuan import HanShuDaoShuYunSuan
from mathsolver.functions.hanshu.dingyiyu import QiuDingYiYu
from mathsolver.functions.hanshu.helper import check_inter
from mathsolver.functions.hanshu.zhiyu import hanshuzuixiaozhi, hanshuzuidazhi
from mathsolver.functions.zhixian.fangcheng import SolveFangChengDianXie


class DaoShuQieXianXieLvFanWei001ZuiXiao(BaseFunction):
    """利用导数解决切线斜率范围/最值问题 -- 类型一"""
    hanshu = hanshuzuixiaozhi

    def solver(self, *args):
        func = args[0]
        if len(args) == 2:
            qujian = check_inter(args[1])
        else:
            qujian = S.Reals

        # 求函数定义域
        dingyiyu = QiuDingYiYu().solver(func)
        qujian = dingyiyu.intersect(qujian)

        # 求函数导数
        deriv = HanShuDaoShuYunSuan().solver(func).output[0]
        self.steps.append(["", "对函数求导得 {}".format(deriv.printing())])

        # 求最值
        zuizhi_solver = self.hanshu().solver(deriv, qujian)
        self.steps.extend(zuizhi_solver.steps)

        self.output = zuizhi_solver.output
        self.label.add("利用导数解决切线斜率范围/最值问题")
        return self


class DaoShuQieXianXieLvFanWei001ZuiDa(DaoShuQieXianXieLvFanWei001ZuiXiao):
    """利用导数解决切线斜率范围/最值问题 -- 类型一"""
    hanshu = hanshuzuidazhi


class DaoShuQieXianXieLvFanWei002ZuiXiao(BaseFunction):
    """利用导数解决切线斜率范围/最值问题 -- 类型二"""
    hanshu = DaoShuQieXianXieLvFanWei001ZuiXiao

    def solver(self, *args):
        func = args[0]

        # 求函数导数
        deriv = HanShuDaoShuYunSuan().solver(func).output[0]

        # 求切线斜率最值
        step_solver = self.hanshu().solver(*args)
        self.steps.extend(step_solver.steps)
        zuizhi = step_solver.output[0].value

        # 求切点坐标
        x = solve(deriv.expression - 3, domain=S.Reals)[0]
        y = func.expression.subs(func.var, x)
        self.steps.append(["", "切点坐标为 (%s, %s)" % (x, y)])

        # 点斜式求方程
        xielv_solver = SolveFangChengDianXie().solver(BasePoint({"name": "", "value": [x, y]}), BaseNumber(zuizhi))
        self.steps.extend(xielv_solver.steps)

        self.output = xielv_solver.output
        self.label.add("利用导数解决切线斜率范围/最值问题")
        return self


class DaoShuQieXianXieLvFanWei002ZuiDa(DaoShuQieXianXieLvFanWei002ZuiXiao):
    hanshu = DaoShuQieXianXieLvFanWei001ZuiDa


if __name__ == '__main__':
    pass
